package com.example.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.example.reggie.common.BaseContext;
import com.example.reggie.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();
        StringBuffer url = request.getRequestURL();
        log.info("uri:{}",uri);
        log.info("url:{}",url);
        String[] notChecks = {
                "/employee/login",
                "/employee/loginout",
                "/backend/**",
                "/front/**",
                "/user/login"};
        boolean checkd = checkUri(uri,notChecks);
        if (checkd) {
            filterChain.doFilter(request,response);
            return;
        }
        if (request.getSession().getAttribute("employee") != null) {
            BaseContext.setThreadLocal((Long) request.getSession().getAttribute("employee"));
            filterChain.doFilter(request,response);
            return;
        }
        if (request.getSession().getAttribute("user") != null) {
            BaseContext.setThreadLocal((Long) request.getSession().getAttribute("user"));
            filterChain.doFilter(request,response);
            return;
        }
        log.info("请求被拦截");
        response.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
    }

    private boolean checkUri(String uri, String[] notChecks) {
        for (String notCheck : notChecks){
            boolean check = PATH_MATCHER.match(notCheck,uri);
            if (check){
                return true;
            }
        }
        return false;
    }
}
